"""
功能描述：配置邮件属性，对外提供发送邮件的方法
编写人：guodan
编写日期：2022-1-4
实现逻辑：
导包
    1-创建SendEmail类
    2-实例化方法
        2.1-配置邮箱属性（发件人、收件人，邮件服务器server，主题，用户名，密码，邮件内容）
        2.2-添加附件
    3-封装邮件的内容和附件
    4-对外提供发送邮件的方法
        4.1-连接服务器
        4.2-登录
        4.3-发送
        4.4-关闭连接

"""
import os
import time
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from common.logs import logger
from common.readConfig import ReadConfig


rc = ReadConfig()

class SendEmail():
    def __init__(self):
        """
        配置邮件属性
        """
        self.sender = rc.getdata('email','sender')
        self.receiver = rc.getdata('email','receiver')
        self.username = self.sender
        self.password = rc.getdata('email','password')
        self.smtpserver = rc.getdata('email','smtpserver')
        #邮箱主题
        t = time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())
        self.subject = t + 'appiumUI自动化测试报告'
        self.report_dir = os.path.dirname(os.path.dirname(__file__)) + '/report/'

    def __conf(self,file):
        """封装邮件内容,组装邮件内容和附件"""
        report = file
        #读取附件文件内容
        with open(report,'rb') as f:
            mail_body = f.read()
            #配置附件内容
            self.msg = MIMEMultipart()
            att = MIMEText(mail_body,'plain','utf-8')
            att['Content-Type'] = 'application/octet-stream'
            att['Content-Disposition'] = 'attachment;filename=report.html'
            #添加附件
            self.msg.attach(att)

            content = '这是appium自动化测试报告，具体详情请查看附件！'
            self.msg.attach(MIMEText(content, 'plain', 'utf-8'))
            self.msg['Subject'] = Header(self.subject, 'utf-8')
            self.msg['From'] = self.sender
            self.msg['To'] = self.receiver


    def sendEmail(self,file):
        """连接服务器，发送邮件"""
        self.__conf(file)
        try:
            sm = SMTP()
            sm.connect(self.smtpserver)
            sm.login(self.username,self.password)
            sm.sendmail(self.sender,self.receiver,self.msg.as_string())
        except Exception as msg:
            logger.error(f"邮件发送失败，提示：{msg}")
        finally:
            sm.quit()


if __name__ == '__main__':
    se = SendEmail()
    report = os.path.dirname(os.path.dirname(__file__)) + '/report/'



